package com.deyuanyun.pic.ctrl.controller;

import java.io.InputStream;
import java.util.Date;
import java.util.List;
import java.util.Map;

import javax.annotation.Resource;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.servlet.ModelAndView;

import com.deyuanyun.pic.common.dto.PageJsonBean;
import com.deyuanyun.pic.common.util.MyCollectionUtil;
import com.deyuanyun.pic.common.util.StringUtils;
import com.deyuanyun.pic.common.util.ajax.AjaxSupport;
import com.deyuanyun.pic.common.util.poi.ReadExcel;
import com.deyuanyun.pic.common.util.web.Asserts;
import com.deyuanyun.pic.common.validator.imlclass.BeanValidateUtil;
import com.deyuanyun.pic.common.validator.imlclass.VResult;
import com.deyuanyun.pic.ctrl.controller.dto.CathRepairTaskQueryVO;
import com.deyuanyun.pic.ctrl.controller.dto.RepairEQPTRecordExcelVO;
import com.deyuanyun.pic.ctrl.controller.dto.RepairEQPTSuggestExcelVO;
import com.deyuanyun.pic.ctrl.domain.CpRecRecode;
import com.deyuanyun.pic.ctrl.domain.CpRecTask;
import com.deyuanyun.pic.ctrl.enumeration.EqptTypeEnum;
import com.deyuanyun.pic.ctrl.service.CathRepairTaskService;
import com.deyuanyun.pic.ctrl.service.ExternalInspProjectService;
import com.deyuanyun.pic.pipe.controller.BaseController;

/**
 *  阴保设备整改_阴保整改任务Controller
 *
 * @author ChenKui
 * @date 2016-06-16
 */
@Controller
@RequestMapping("/corrctrl/CathRepairTask")
public class CathRepairTaskController extends BaseController{

    private @Autowired CathRepairTaskService cathRepairTaskService;//缺陷任务相关
    private @Resource ExternalInspProjectService externalInspProjectService;

    //进入阴保整改任务列表页面
    @RequestMapping("/init.html")
    public ModelAndView init(ModelMap model) {
        //阴保整改任务状态
        //model.addAttribute("repairTaskStateds", RepairTaskStatedEnum.values());
        //AjaxSupport.sendSuccessText("success", model.asMap());
        return forword("/corrctrl/repair/cathList", model);
    }

    //进入创建阴保整改任务页面
    @RequestMapping("/initCreate.html")
    public ModelAndView initCreate(ModelMap model) {
        
        //AjaxSupport.sendSuccessText("success", model.asMap());
        return forword("/corrctrl/repair/cathCreate", model);
    }

    //进入缺陷点详情界面
    @RequestMapping("/initDetail.html")
    public ModelAndView initDetail(ModelMap model) {
        
        //AjaxSupport.sendSuccessText("success", model.asMap());
        return forword("/corrctrl/repair/cathDetails", model);
    }

    //进入整改效果
    @RequestMapping("/cathEffect.html")
    public ModelAndView cathEffect(ModelMap model) {
        
        //AjaxSupport.sendSuccessText("success", model.asMap());
        return forword("/corrctrl/repair/cathEffect", model);
    }
    /**
     * 查询阴保整改任务列表
     * 
     * @param repairTaskQuery
     * @param model
     */
    @RequestMapping("/queryRepairTaskList.json")
    @ResponseBody
    public void queryRepairTaskList(CathRepairTaskQueryVO repairTaskQuery,ModelMap model) {
        PageJsonBean jsonBean = new PageJsonBean();
        List<CpRecTask> repairTaskList = cathRepairTaskService.queryRepairTaskList(repairTaskQuery);
        //model.addAttribute("repairTaskList", repairTaskList);
        jsonBean.setList(repairTaskList);
        AjaxSupport.sendSuccessText("success", jsonBean);
        //return forword("/pbf/queryRepairTaskList.jsp", model);
    }

    /**
     * 查询某一任务的详情（含具体缺陷点）
     * 
     * @param repairTaskId
     * @param model
     * @return
     */
    @RequestMapping("/queryDetail.json")
    @ResponseBody
    public void queryDetail(@RequestParam("repairTaskId") String repairTaskId,ModelMap model) {
        
        //查询阴保整改任务的详情信息
        CathRepairTaskQueryVO repairTaskVO = new CathRepairTaskQueryVO();
        repairTaskVO.setRepairTaskIds(new String[]{repairTaskId});
        List<CpRecTask> repairTaskList = cathRepairTaskService.queryRepairTaskList(repairTaskVO);
        Asserts.assertTrue(repairTaskList != null && !repairTaskList.isEmpty(), "没有找到对应阴保整改任务记录");
        
        CpRecTask repairTask = repairTaskList.get(0);
        model.addAttribute("repairTask", repairTask);
        
        PageJsonBean jsonBean = new PageJsonBean();
        //查询阴保整改任务对应的缺陷点
        List<CpRecRecode> defectInfoList = cathRepairTaskService.queryRepairRecodeList(repairTaskId,null);
        jsonBean.setList(defectInfoList);
        model.addAttribute("defectInfoList", jsonBean);
        
        List<CpRecRecode> defectInfoTestStationList = cathRepairTaskService.queryRepairRecodeList(repairTaskId,EqptTypeEnum.CPTESTSTATION);
        model.addAttribute("includeTestStation", defectInfoTestStationList != null && !defectInfoTestStationList.isEmpty());
        
        AjaxSupport.sendSuccessText("success", model);
        //return forword("/pbf/queryDetail", model);
    }


    /**
     * 直接保存
     */
    @RequestMapping("/createOrUpdate2.json")
    @ResponseBody
    public void createOrUpdate2(CpRecTask repairTask
            ,@RequestParam(value = "defectInfoExcelFile",required = false) MultipartFile defectInfoExcelFile) {
        
        CpRecRecode[] cpRecRecodes = null;
        if(StringUtils.isEmpty(repairTask.getId())){//仅新建的时候比传文件
            Asserts.assertTrue(defectInfoExcelFile != null && !defectInfoExcelFile.isEmpty(), "上传文件不能为空");
        }
        if(defectInfoExcelFile != null && !defectInfoExcelFile.isEmpty()){
            List<RepairEQPTSuggestExcelVO> rediExcelList;
            VResult b;
            InputStream is = null;
            try {
                is = defectInfoExcelFile.getInputStream();
                // 从Excel中读取进来
                rediExcelList = ReadExcel.readExcle(RepairEQPTSuggestExcelVO.class, is, 3);

                // 哎，从没见过写公共方法抛这么多莫名其妙的Exception出来的。
                // 吐槽：读Excel出现异常可以理解，但是删除空白行也抛显示异常是什么意思？做一个验证也抛显示异常。醉了。
                rediExcelList = MyCollectionUtil.removeLastEmpty(rediExcelList);// 删掉尾部空白行
                b = BeanValidateUtil.vali2(rediExcelList, 3 + "");// TODO CK待验证：这个地方为什么是从4开始？用来提示第几行有误。
                
            } catch (Exception e) {
                logger.error("处理Excel文件出现异常", e);
                AjaxSupport.sendFailText("Fail", "操作失败：无法读取Excel。<br />原因：" + e.getMessage());
                return;
            } finally{
                try {
                    is.close();
                } catch (Exception e2) {
                }
            }
            Asserts.assertTrue(b.isRelult(), b.getAllString());
            cpRecRecodes = new CpRecRecode[rediExcelList.size()];
            cpRecRecodes = rediExcelList.toArray(cpRecRecodes);
        }
        
        
        cathRepairTaskService.createOrUpdate(repairTask, cpRecRecodes);
        
        AjaxSupport.sendSuccessText("success", "");
    }
    

    /**
     * 导入整改记录
     */
    @RequestMapping("/createOrUpdateRecord.json")
    @ResponseBody
    public void createOrUpdateRecord(String repairTaskId
            ,@RequestParam(value = "recordExcelFile") MultipartFile defectInfoExcelFile) {
        
        Asserts.assertTrue(defectInfoExcelFile != null && !defectInfoExcelFile.isEmpty(), "上传文件不能为空");

        List<RepairEQPTRecordExcelVO> rediExcelList;
        VResult b;
        InputStream is = null;
        try {
            is = defectInfoExcelFile.getInputStream();
            
            // 从Excel中读取进来
            rediExcelList = ReadExcel.readExcle(RepairEQPTRecordExcelVO.class, is, 3);

            // 哎，从没见过写公共方法抛这么多莫名其妙的Exception出来的。
            // 吐槽：读Excel出现异常可以理解，但是删除空白行也抛显示异常是什么意思？做一个验证也抛显示异常。醉了。
            rediExcelList = MyCollectionUtil.removeLastEmpty(rediExcelList);// 删掉尾部空白行
            b = BeanValidateUtil.vali2(rediExcelList, 3 + "");// TODO CK待验证：这个地方为什么是从4开始？
            
        } catch (Exception e) {
            logger.error("处理Excel文件出现异常", e);
            AjaxSupport.sendFailText("Fail", "操作失败：无法读取Excel。<br/>原因：" + e.getMessage());
            return;
        } finally{
            try {
                is.close();
            } catch (Exception e2) {
            }
        }
        Asserts.assertTrue(b.isRelult(), b.getAllString());
        
        CpRecRecode[] cpRecRecodes = new CpRecRecode[rediExcelList.size()];
        cpRecRecodes = rediExcelList.toArray(cpRecRecodes);
        cathRepairTaskService.createOrUpdateRecord(repairTaskId, cpRecRecodes);
        
        AjaxSupport.sendSuccessText("success", "");
    }
    
    
    /**
     * 删除任务
     * 
     * @param repairTaskIds
     */
    @RequestMapping("/updateToDelete.json")
    @ResponseBody
    public void updateToDelete(@RequestParam("repairTaskId") String[] repairTaskIds,ModelMap model) {
        
        int secc = cathRepairTaskService.updateToDelete(repairTaskIds);
        model.addAttribute("successCount", secc);
        model.addAttribute("count", repairTaskIds.length);
        AjaxSupport.sendSuccessText("success", model);
    }
    
    

    /**
     * 阴保整改对比效果
     * 
     * @param repairTaskIds
     */
    @RequestMapping("/queryCathRepairTaskEffect.json")
    @ResponseBody
    public void queryCathRepairTaskEffect(@RequestParam("repairTaskId") String repairTaskId
            ,@RequestParam("testingDate") Date testingDate ,ModelMap model) {

        List<Map<String,Object>> list = cathRepairTaskService.queryCathRepairTaskEffect(repairTaskId, testingDate);
        AjaxSupport.sendSuccessText("success", list);
    }
    
    
    
    
    
}
